package com.team06.config;

import com.team06.listener.XmlFileListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Configuration
public class FileMonitorConfig {


    @Autowired
    private XmlFileListener xmlFileListener; // 自动注入监听器

    @Value("${xml.monitor.directory}")
    private String monitorDirectory;

    @Bean(initMethod = "start", destroyMethod = "stop")
    public FileAlterationMonitor fileAlterationMonitor() {
        // 监听的目录
        File directory = new File(monitorDirectory);
        FileAlterationObserver observer = new FileAlterationObserver(directory);

        // 使用自动注入的监听器，而不是 new 一个新的
        observer.addListener(xmlFileListener);

        // 监听间隔时间，单位为毫秒
        long interval = TimeUnit.SECONDS.toMillis(5);
        return new FileAlterationMonitor(interval, observer);
    }
}